package com.nineclock.common.filter;

import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@WebFilter("/*")
public class CurrentUserFilter extends GenericFilterBean {
    /**
     * 获取 认证信息
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            //获取上下文对象
            SecurityContext context = SecurityContextHolder.getContext();
            //获取认证信息
            Authentication authentication = context.getAuthentication();

            String name = authentication.getName();
            if(name != null && !name.equals("anonymousUser")){
                //把json串转换为 UserInfo类型
                UserInfo userInfo = JsonUtils.toBean(name, UserInfo.class);
                //存储到当前线程
                CurrentUserHolder.set(userInfo);
            }
            //放行
            chain.doFilter(request, response);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } finally {
            CurrentUserHolder.remove();
        }
    }
}
